/* eslint-disable import/no-anonymous-default-export */
/* eslint-disable jsx-a11y/anchor-is-valid */

import "./style.scss";
import { UserContext } from "../../store/user";
import React, { useState, useEffect } from "react";
import AiLogo from "../../assets/img/aipin-logo.png";
import * as Api from '../../api/login'
import requestSmsCode from '../../api/sms'
import { useLocation, useNavigate } from "react-router";

import { Flex, Radio, Button } from 'antd';
const options = [
  { label: '求职方', value: 'qiu_zhi' },
  { label: '招聘方', value: 'zhao_pin' },
];

export default () => {
  const userObj = React.useContext(UserContext);
  // console.log('用户信息: ', userObj)

  const navigate = useNavigate();
  const location = useLocation();
  // console.log('location=', location)
  // let {from:{pathname:pageFrom}, userType:originalUserType} = location.state
  const [pageFrom, setPageFrom] = useState('')

  const [isCaptcha, setIsCaptcha] = useState(false);
  const [secs, setSecs] = useState(59);
  const [phone, setPhone] = useState('')
  const [captCha, setCaptCha] = useState('')
  const [isValidatePhone, setIsValidatePhone] = useState(false)
  const [isValidateCode, setIsValidateCode] = useState(false)
  const [tip, setTip] = useState('')

  const [userType, setUserType] = useState('qiu_zhi')

  const [loading, setLoading] = useState(false)

  useEffect(()=>{
    if( sessionStorage['user-type-tab'] ){
      setUserType(sessionStorage['user-type-tab'])
      setPageFrom((sessionStorage['user-type-tab']==='qiu_zhi') ? '/profile':'/recruitmanage')
    }

    delete sessionStorage['user-type-tab'];
  }, [])

  useEffect(()=>{
    let timer;
    if( isCaptcha ){

      if( secs === 0 ){
        clearInterval(timer)
        setIsCaptcha(false);
        return;
      }

      timer = setInterval(()=>{
        // console.log('secs=', secs)
        setSecs(nowSec=>nowSec - 1)
      }, 1000);
    }

    return ()=>{
      clearInterval(timer)
    }
  }, [isCaptcha, secs]);

  return (
    <div className="font-sans text-gray-800 min-h-screen flex flex-col login-page">
      <header className="fixed top-0 left-0 right-0 z-50 bg-white bg-opacity-95 shadow-sm">
        <div className="container mx-auto px-4 py-4 flex justify-between items-center">
          <a>
            <img className="block" src={AiLogo} alt="" width="100" />
          </a>
        </div>
      </header>
      <main className="flex-grow pt-24 pb-16 auth-background">
        <div className="container mx-auto px-4 max-w-5xl">
          <div className="bg-white rounded-xl shadow-lg overflow-hidden mx-auto">
            <div className="flex flex-col md:flex-row">
              <div className="md:w-2/5 bg-primary p-8 text-white flex flex-col justify-center">
                <h2 className="text-3xl font-bold mb-6">欢迎加入艾聘</h2>
                <p className="mb-8">
                  AI
                  驱动的新一代智能招聘平台，为您提供精准的职业机会和全方位的职业发展支持。
                </p>
                <div className="space-y-6">
                  <div className="flex items-start">
                    <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center mr-4 flex-shrink-0">
                      <div className="w-5 h-5 flex items-center justify-center text-white">
                        <i className="ri-search-line"></i>
                      </div>
                    </div>
                    <div>
                      <h3 className="font-semibold mb-1">智能职位匹配</h3>
                      <p className="text-sm text-white/80">
                        基于您的技能和偏好，智能推荐最适合的职位
                      </p>
                    </div>
                  </div>
                  <div className="flex items-start">
                    <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center mr-4 flex-shrink-0">
                      <div className="w-5 h-5 flex items-center justify-center text-white">
                        <i className="ri-user-star-line"></i>
                      </div>
                    </div>
                    <div>
                      <h3 className="font-semibold mb-1">专业能力认证</h3>
                      <p className="text-sm text-white/80">
                        全面展示您的专业能力，提升求职竞争力
                      </p>
                    </div>
                  </div>
                  <div className="flex items-start">
                    <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center mr-4 flex-shrink-0">
                      <div className="w-5 h-5 flex items-center justify-center text-white">
                        <i className="ri-road-map-line"></i>
                      </div>
                    </div>
                    <div>
                      <h3 className="font-semibold mb-1">职业发展规划</h3>
                      <p className="text-sm text-white/80">
                        获取个性化的职业发展建议和学习资源
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              <div className="md:w-3/5 p-8">
                <div className="mb-4">
                  {/* <div className="flex border-b border-gray-200">
                    <button
                      id="login-tab"
                      className="tab-btn py-3 px-6 font-medium text-primary border-b-2 border-primary"
                    >
                      短信登录
                    </button>
                  </div> */}
                  <Flex vertical gap="middle">
                    <Radio.Group
                      block
                      options={options}
                      optionType="button"
                      buttonStyle="solid"
                      value={userType}
                      onChange={(ev)=>{
                        console.log(ev);
                        setUserType(ev.target.value)
                        setIsCaptcha(false)
                        setSecs(59)
                        setCaptCha('')
                        setIsValidatePhone(false)
                        setIsValidateCode(false)
                        setTip('')

                        // pageFrom = (ev.target.value==='qiu_zhi') ? '/profile':'/recruitmanage'
                        setPageFrom((ev.target.value==='qiu_zhi') ? '/profile':'/recruitmanage')
                      }}
                    />
                  </Flex>
                </div>
                <div id="login-content" className="tab-content active">
                  <div className="text-xs mb-2" style={{ color: "#858585" }}>
                    验证即登录，未注册将自动创建艾聘账号
                  </div>
                  <form autoComplete="off">
                    <div className="mb-6">
                      <label
                        htmlFor="login-username"
                        className="block text-sm font-medium text-gray-700 mb-2"
                      >
                        手机号
                      </label>
                      <div className="relative">
                        <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></div>
                        <input
                          type="number"
                          id="login-username"
                          className={"form-input pl-10 border border-[#e5e7eb] focus:border-primary " + (isValidatePhone? 'border-error':'')}
                          placeholder="请输入手机号"
                          autoComplete="new-password"
                          value={phone}
                          onChange={(ev)=>{
                            let str = ev.target.value.trim()
                            if( str ){
                              setIsValidatePhone(false)
                            }
                            setPhone(str)
                          }}
                        />
                      </div>
                    </div>
                    <div className="mb-4">
                      <div className="flex justify-between items-center mb-2">
                        <label
                          htmlFor="login-password"
                          className="block text-sm font-medium text-gray-700"
                        >
                          验证码
                        </label>
                      </div>
                      <div className="relative">
                        <input
                          type="tel"
                          id="login-password"
                          maxLength="6"
                          className={"form-input pl-10 border border-[#e5e7eb] focus:border-primary " + (isValidateCode ? 'border-error':'')}
                          placeholder="请输入验证码"
                          value={captCha}
                          onChange={(ev)=>{
                            let str = ev.target.value.trim()
                            if( str){
                              setIsValidateCode(false)
                            }
                            setCaptCha(str)
                          }}
                        />
                        {isCaptcha ? (
                          <a
                            className="text-base absolute whitespace-nowrap right-5 top-[50%] translate-y-[-50%] text-[#666]"
                          >
                            {secs}s
                          </a>
                        ) : (
                          <a
                            className="text-base text-primary absolute whitespace-nowrap right-5 top-[50%] translate-y-[-50%]"
                            onClick={(ev)=>{
                              ev.preventDefault();
                              let _val = phone.replace(/\D/g, '')
                              if( !_val){
                                setIsValidatePhone(true);
                                setTip('请填写正确的手机号');
                                return;
                              }

                              if( _val.length !== 11 ){
                                setIsValidatePhone(true);
                                setTip('手机号11位数字');
                                return;
                              }
                              requestSmsCode(phone)
                              setIsCaptcha(true);
                            }}
                          >
                            发送验证码
                          </a>
                        )}
                      </div>
                    </div>
                    {
                      isValidatePhone || isValidateCode ? (<div className="text-error mb-3">{tip}</div>) : (<div className="text-error mb-3">&nbsp;</div>)
                    }
                    <Button type="primary" size="large" disabled={!(phone && captCha)} block loading={loading} onClick={()=>{
                      let _val = phone.replace(/\D/g, '')
                      if( _val.length !== 11 ){
                        setIsValidatePhone(true);
                        setTip('请填写正确的手机号');
                        return;
                      }

                      _val = captCha.replace(/\D/g, '')
                      if( _val.length !== 6 ){
                        setIsValidateCode(true);
                        setTip('验证码6位数字');
                        return;
                      }

                      setLoading(true)
                     ;(async()=>{
                      try {
                        let ret = await Api.login({
                          "loginBizId": phone, // phone, // "13800138000"
                          "smsCode": captCha,
                          userType: userType==='qiu_zhi' ? 0 : 1, // 0应聘方，1招聘方
                        })
  
                        console.log('返回ret: ', ret, ', 来源页: ', pageFrom)
                        if( ret.code == 200 ){
                          // userObj.login
                          userObj.login(ret.result)
                          navigate(pageFrom, { replace: true })
                        }
                      } catch (err) {
                        console.log(err);
                      }

                      setLoading(false)
                     })();

                    }} >登录</Button>
                    <div className="mt-8 relative">
                      <div className="absolute inset-0 flex items-center">
                        <div className="w-full border-t border-gray-200"></div>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
      <footer className="bg-gray-100 py-6">
        <div className="container mx-auto px-4">
          <div className="flex flex-col md:flex-row justify-between items-center">
            <p className="text-gray-500 text-sm mb-4 md:mb-0">
              © 2025 艾聘 AIPIN. 保留所有权利
            </p>
            <div className="flex space-x-4">
              <a href="#" className="text-gray-500 hover:text-gray-700 text-sm">
                关于我们
              </a>
              <a href="#" className="text-gray-500 hover:text-gray-700 text-sm">
                隐私政策
              </a>
              <a href="#" className="text-gray-500 hover:text-gray-700 text-sm">
                用户协议
              </a>
              <a href="#" className="text-gray-500 hover:text-gray-700 text-sm">
                帮助中心
              </a>
            </div>
          </div>
        </div>
      </footer>
    </div>
  );
};
